package com.wude.guild.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mc.developmentkit.bean.GetPaidInfo;
import com.mc.developmentkit.bean.LinkAgeInfo;
import com.mc.developmentkit.callback.AliPayListener;
import com.mc.developmentkit.callback.LinkAgeListener;
import com.mc.developmentkit.pay.MCThirdPartyPay;
import com.mc.developmentkit.utils.ToastUtil;
import com.mc.developmentkit.views.LinkAgeWindow;
import com.umeng.analytics.MobclickAgent;
import com.wude.bean.UserInfo;
import com.wude.guild.R;
import com.wude.guild.servercore.app.CubeFragment;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.Utils;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/11/23 0023.
 */
@SuppressLint("HandlerLeak")
public class PayZheKouFragment extends CubeFragment implements View.OnClickListener, AliPayListener {
    private TextView name;
    private View xuanze;
    private TextView gamename;
    private EditText qian;
    private TextView bili;
    private TextView jine;
    private TextView bangjin;
    private CheckBox zfb;
    private CheckBox wx;
    private TextView queren;
    private Double discount = 10.0;
    private List<LinkAgeInfo> linkAgeInfos;
    private LinkAgeWindow linkAgeWindow;
    private String game_id;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return null;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("PayZheKouFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("PayZheKouFragment");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_pay_zhekou, null);
        initview(inflate);
        return inflate;
    }

    private void initview(View v) {
        name = v.findViewById(R.id.name);
        gamename = v.findViewById(R.id.gamename);
        bili = v.findViewById(R.id.bili);
        jine = v.findViewById(R.id.jine);
        bangjin = v.findViewById(R.id.bangjin);
        xuanze = v.findViewById(R.id.xuanze);
        qian = v.findViewById(R.id.qian);
        queren = v.findViewById(R.id.queren);

        zfb = v.findViewById(R.id.zfb);
        wx = v.findViewById(R.id.wx);
        xuanze.setOnClickListener(this);
        queren.setOnClickListener(this);
        zfb.setChecked(true);
        zfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    wx.setChecked(false);
                }
            }
        });
        wx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    zfb.setChecked(false);
                }
            }
        });

        qian.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String s1 = s.toString();
                if (!s1.equals("")) {
                    Double integer = Double.valueOf(s1);
                    Double i = integer * (discount / 10);
                    DecimalFormat df = new DecimalFormat("######0.00");
                    String format = df.format(i);
                    jine.setText(format + "元");
                    bangjin.setText(integer + "个");
                } else {
                    jine.setText("");
                    bangjin.setText("");
                }
            }
        });

        UserInfo loginUser = Utils.getLoginUser();
        name.setText(loginUser.account);

        HashMap<String, String> map = new HashMap<>();
        map.put("version", "1");
        map.put("token", loginUser.token);
        HttpCom.POST(handler, HttpCom.getDCGameURL(), map, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.queren:
                Pay();
                break;
            case R.id.xuanze:
                XuanZe();
                break;
        }
    }

    private void XuanZe() {
        if (linkAgeInfos != null) {
            if (linkAgeWindow == null) {
                linkAgeWindow = new LinkAgeWindow(getActivity());
            }
            /**
             * 参数依次为：宽度，高度，显示位置，List（LinkAge），回调，是否显示联动
             */
            linkAgeWindow.showPop(xuanze.getWidth(), 500, xuanze, linkAgeInfos, linkAgeListener, false);
            linkAgeWindow.popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        } else {
            ToastUtil.showToast("当前无代充游戏");
        }

    }


    LinkAgeListener linkAgeListener = new LinkAgeListener() {
        @Override
        public void checkedResult(String s, int i) {
            game_id = i + "";
            gamename.setText(s);       //选中的游戏设置在TextView上
            HashMap<String, String> map = new HashMap<>();
            map.put("game_id", i + "");
            Log.e("获取折扣信息", map.toString());
            HttpCom.POST(zHandler, HttpCom.getDiscountURL(), map, false);
        }
    };


    /**
     * 获取折扣
     */
    Handler zHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    discount = HttpUtils.DNSDiscount(msg.obj.toString());
                    if (discount != 0) {
                        jine.setText("");
                        qian.setText("");
                        bangjin.setText("");
                        bili.setText(discount + "折");
                    } else {
                        bili.setText(10.00 + "折");
                        discount = 10.0;
                        qian.setText("");
                        bangjin.setText("");
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };

    /**
     * 获取可代充游戏列表
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    linkAgeInfos = HttpUtils.DNSGameCanPay(msg.obj.toString());
                    break;
                case 2:

                    break;
            }
        }
    };


    /**
     * 点击确认按钮支付
     */
    private void Pay() {
        String jine1 = qian.getText().toString();
        String s = gamename.getText().toString();
        if (s.equals("请选择充值游戏")) {
            ToastUtil.showToast("请选择充值游戏");
            return;
        }
        if (jine1.equals("")) {
            ToastUtil.showToast("请输入充值金额");
            return;
        }
        if (!zfb.isChecked() && !wx.isChecked()) {
            ToastUtil.showToast("请选择一种支付方式");
            return;
        }
        UserInfo loginUser = Utils.getLoginUser();
        GetPaidInfo getPaidInfo = new GetPaidInfo();
//        getPaidInfo.pay_amount = jine1;                 //应付金额
        getPaidInfo.pay_amount = Utils.getBase64String(jine1.getBytes(), 0);
        getPaidInfo.good_type = 2;                      //1平台币   2绑币
        getPaidInfo.user_sign = loginUser.token;        //用户token
        getPaidInfo.promote_id = "1";                   //推广员id
        getPaidInfo.game_id = game_id;                   //游戏id

        if (zfb.isChecked()) {
            getPaidInfo.payType = "1";                  //支付宝
            ZFB(getPaidInfo);
        } else if (wx.isChecked()) {
            getPaidInfo.payType = "2";                  //微信
            WX(getPaidInfo);
        }
    }


    public boolean jin(String a) {
        String substring = a.substring(0, 1);
        int i = Integer.parseInt(substring);
        if (i >= 1) {
            return true;
        }
        return false;
    }

    /**
     * 微信支付
     */
    private void WX(GetPaidInfo info) {
        MCThirdPartyPay.getInstance().wxPay(getActivity(), HttpCom.getPayUrl(), info);
    }

    /**
     * 支付宝支付
     */
    private void ZFB(GetPaidInfo info) {
        MCThirdPartyPay.getInstance().aliPay(getActivity(), HttpCom.getPayUrl(), info, this);
    }

    @Override
    public void zfbPayResult(String s) {
        Log.e("支付宝返回", s);
    }
}
